/*
 * Copyright© 2015 lindaojiang. All rights reserved.
 */

package com.zhengda.carapp.tool;

import android.util.Base64;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class DataCoding {
    private static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
    private static final byte[] IVInit = "XcKi0k89".getBytes(); //向量

    public static String encode(String encryptString, String encryptKey) throws Exception {
        DESKeySpec dks = new DESKeySpec(encryptKey.getBytes());
        Key secretKey = SecretKeyFactory.getInstance("DES").generateSecret(dks);

        IvParameterSpec paramSpec = new IvParameterSpec(IVInit);

        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(encryptString.getBytes("UTF-8"));
        return new String(Base64.encode(bytes, Base64.DEFAULT), "UTF-8");
    }

    public static String decode(byte[] decryptBytes, String decryptKey) throws Exception {
        byte[] data = Base64.decode(decryptBytes, Base64.DEFAULT);

        DESKeySpec dks = new DESKeySpec(decryptKey.getBytes());
        Key secretKey = SecretKeyFactory.getInstance("DES").generateSecret(dks);

        IvParameterSpec paramSpec = new IvParameterSpec(IVInit);

        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(data), "UTF-8");
    }
}
